package com.eonmind.pay.service.impl;

import com.eonmind.common.contract.data.response.ResponseEntity;
import com.eonmind.common.contract.enums.DelEnum;
import com.eonmind.common.contract.timer.Timer;
import com.eonmind.common.provider.entity.pay.Cart;


import com.eonmind.common.provider.entity.vip.VipPackage;
import com.eonmind.common.provider.entity.vip.VipPackage;
import com.eonmind.pay.PayApplication;
import com.eonmind.pay.dto.CartDto;
import com.eonmind.pay.enums.TradeState;
import com.eonmind.pay.mapper.CartMapper;
import com.eonmind.pay.service.CartService;
import com.mongoplus.conditions.query.QueryWrapper;
import com.mongoplus.conditions.update.UpdateWrapper;
import com.mongoplus.service.IService;
import com.mongoplus.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName CartServiceImpl
 * @Description TODO
 * Author 32004
 * Date 2025/5/20 15:08
 * Version 1.0
 **/

@Service
public class CartServiceImpl extends ServiceImpl<Cart> implements CartService {

    @Resource
    CartMapper cartMapper;

    @Override
    public ResponseEntity<CartDto> getListByUserId(Long id) {
        List<Cart> list= cartMapper.selectList(id);
        List<CartDto.CartItemDto> cartList = list.stream().map(item -> {
            CartDto.CartItemDto cartItemDto = new CartDto.CartItemDto();
            cartItemDto.setCount(item.getCount());
            VipPackage menu= PayApplication.vipMap.get(item.getProductId());
            //TODO 远程调用获取套餐价格
            cartItemDto.setMenu(menu);
            return cartItemDto;
        }).collect(Collectors.toList());
        return ResponseEntity.success(new CartDto(cartList));
    }

    @Override
    public ResponseEntity addCartByUserId(Cart cart, Long userId) {
        if(cart.getStatus()!=null&&cart.getStatus()==TradeState.ADD.getCode()){

            if(cart.getCount()==0){
                cartMapper.removeCart(userId,cart.getProductId());
            }else{
                cartMapper.updateCartCount(userId,cart.getProductId(),cart.getCount());
            }
        }else{
            cart.setUserId(userId);
            cart.setStatus(TradeState.ADD.getCode());
            cart.setCreateTime(Timer.currentTimestamp());
            cart.setUpdateTime(Timer.currentTimestamp());
            cart.setCount(1);
            this.save(cart);
        }
        return ResponseEntity.success("修改成功");
    }

    @Override
    public void updateOrderId(Long id, Long orderId) {
        cartMapper.updateOrderId(id,orderId);
    }
}
